<?php

namespace app\controller\crm;

use app\BaseController;
use app\common\DataPermissionHelper;
use think\facade\Db;
use think\facade\Request;

class Followup extends BaseController
{
    /**
     * 获取客户跟进记录列表
     */
    public function list()
    {
        $params = Request::param();
        $customerId = $params['customer_id'] ?? 0;
        $customerName = $params['customer_name'] ?? '';
        $followupType = $params['followup_type'] ?? '';
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        
        $query = Db::name('crm_followup')
            ->alias('f')
            ->field('f.*, u.name as user_name, c.name as customer_name')
            ->leftJoin('admin u', 'f.user_id = u.id')
            ->leftJoin('crm_customer c', 'f.customer_id = c.id')
            ->where('f.delete_time', 0);
            
        if ($customerId) {
            $query->where('f.customer_id', $customerId);
        }
        
        // 按客户名称模糊搜索
        if ($customerName) {
            $query->where('c.name', 'like', '%' . $customerName . '%');
        }
        
        // 按跟进类型筛选
        if ($followupType !== '') {
            $query->where('f.followup_type', $followupType);
        }
        
        // 数据权限控制
        $userId = $this->getUserId();
        if ($userId > 0) {
            // 获取当前用户信息
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if ($userInfo && $userInfo['group_id'] != 1) { // 非管理员
                $query->where('f.user_id', $userId);
            }
        }
        
        $total = $query->count();
        $list = $query->order('f.create_time', 'desc')
            ->page($page, $limit)
            ->select();
            
        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }
    
    /**
     * 添加跟进记录
     */
    public function add()
    {
        $params = Request::param();
        $userId = $this->getUserId();

        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        // 获取用户部门信息
        $userInfo = Db::name('admin')
            ->field('did')
            ->where('id', $userId)
            ->find();

        $data = [
            'customer_id' => $params['customer_id'],
            'user_id' => $userId,
            'department_id' => $userInfo['did'] ?? 0,
            'followup_type' => $params['followup_type'] ?? 1,
            'followup_time' => isset($params['followup_time']) ? strtotime($params['followup_time']) : time(),
            'followup_result' => $params['followup_result'] ?? 1,
            'content' => $params['content'],
            'next_followup_time' => isset($params['next_followup_time']) ? strtotime($params['next_followup_time']) : 0,
            // 新增字段：机会线索关联
            'opportunity_id' => $params['opportunity_id'] ?? null,
            'followup_category' => $params['followup_category'] ?? 1,
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('crm_followup')->insertGetId($data);

        if ($id) {
            return $this->success(['id' => $id], '添加成功');
        }

        return $this->error('添加失败');
    }
    
    /**
     * 获取跟进记录详情
     */
    public function detail()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        if (!$id) {
            return $this->error('参数错误');
        }
        
        $followup = Db::name('crm_followup')
            ->alias('f')
            ->field('f.*, u.name as user_name, c.name as customer_name')
            ->leftJoin('admin u', 'f.user_id = u.id')
            ->leftJoin('crm_customer c', 'f.customer_id = c.id')
            ->where('f.id', $id)
            ->where('f.delete_time', 0)
            ->find();
            
        if (!$followup) {
            return $this->error('记录不存在');
        }
        
        // 权限检查
        $userInfo = Db::name('admin')
            ->field('id, group_id, did')
            ->where('id', $userId)
            ->find();
        
        if ($userInfo && $followup['user_id'] != $userId && (!isset($userInfo['group_id']) || $userInfo['group_id'] != 1)) {
            return $this->error('无权限查看');
        }
        
        return $this->success($followup, '获取成功');
    }
    
    /**
     * 编辑跟进记录
     */
    public function edit()
    {
        $params = Request::param();
        $id = $params['id'];
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        // 检查权限
        $followup = Db::name('crm_followup')->where('id', $id)->find();
        if (!$followup) {
            return $this->error('记录不存在');
        }
        
        if ($followup['user_id'] != $userId) {
            // 获取用户信息判断是否为管理员
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] != 1)) {
                return $this->error('无权限修改');
            }
        }
        
        $data = [
            'followup_type' => $params['followup_type'] ?? $followup['followup_type'],
            'followup_time' => isset($params['follow_time']) ? strtotime($params['follow_time']) : $followup['followup_time'],
            'followup_result' => $params['followup_result'] ?? $followup['followup_result'],
            'content' => $params['content'] ?? $followup['content'],
            'next_followup_time' => isset($params['next_time']) ? strtotime($params['next_time']) : $followup['next_followup_time'],
            // 新增字段：机会线索关联
            'opportunity_id' => $params['opportunity_id'] ?? $followup['opportunity_id'],
            'update_time' => time()
        ];
        
        $result = Db::name('crm_followup')->where('id', $id)->update($data);
        
        if ($result) {
            return $this->success('更新成功');
        }
        
        return $this->error('更新失败');
    }
    
    /**
     * 删除跟进记录
     */
    public function del()
    {
        $params = Request::param();
        $id = $params['id'];
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        $followup = Db::name('crm_followup')->where('id', $id)->find();
        if (!$followup) {
            return $this->error('记录不存在');
        }
        
        if ($followup['user_id'] != $userId) {
            // 获取用户信息判断是否为管理员
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] != 1)) {
                return $this->error('无权限删除');
            }
        }
        
        $result = Db::name('crm_followup')
            ->where('id', $id)
            ->update(['delete_time' => time()]);
            
        if ($result) {
            return $this->success('删除成功');
        }
        
        return $this->error('删除失败');
    }
    
    /**
     * 获取所有选项（类型+结果）
     */
    public function options()
    {
        $data = [
            'typeOptions' => [
                ['value' => 1, 'label' => '电话联系'],
                ['value' => 2, 'label' => '微信沟通'],
                ['value' => 3, 'label' => '邀约到场'],
                ['value' => 4, 'label' => '上门拜访']
            ],
            'resultOptions' => [
                ['value' => 1, 'label' => '待跟进'],
                ['value' => 2, 'label' => '有意向'],
                ['value' => 3, 'label' => '无意向'],
                ['value' => 4, 'label' => '已合作']
            ]
        ];
        
        return $this->success($data, '获取成功');
    }
    
    /**
     * 获取跟进类型选项
     */
    public function typeOptions()
    {
        $typeOptions = [
            ['value' => 1, 'label' => '电话联系'],
            ['value' => 2, 'label' => '微信沟通'],
            ['value' => 3, 'label' => '邀约到场'],
            ['value' => 4, 'label' => '上门拜访']
        ];
        
        return $this->success($typeOptions, '获取成功');
    }
    
    /**
     * 获取跟进结果选项
     */
    public function resultOptions()
    {
        $resultOptions = [
            ['value' => 1, 'label' => '待跟进'],
            ['value' => 2, 'label' => '有意向'],
            ['value' => 3, 'label' => '无意向'],
            ['value' => 4, 'label' => '已合作']
        ];
        
        return $this->success($resultOptions, '获取成功');
    }
}